/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package controllers;

import java.io.FileInputStream;
import javax.jcr.ImportUUIDBehavior;
import javax.jcr.Node;
import javax.jcr.NodeIterator;
import javax.jcr.Property;
import javax.jcr.PropertyIterator;
import javax.jcr.Repository;
import javax.jcr.RepositoryException;
import javax.jcr.Session;
import javax.jcr.SimpleCredentials;
import javax.jcr.Value;
import org.apache.jackrabbit.core.TransientRepository;

/**
 *
 * @author Spyros
 */
public class JackrabbitExampleController {

    public void execute() throws Exception {
        Repository repository = new TransientRepository();
        Session session = repository.login(
                new SimpleCredentials("username", "password".toCharArray()));
        try {
            Node root = session.getRootNode();
            System.out.println("starting...");
            // Create an unstructured node under which to import the XML
            Node node = root.addNode("importxml", "nt:unstructured");
            FileInputStream xmlStream = new FileInputStream("applicationSample.xml");
            session.importXML(node.getPath(), xmlStream, ImportUUIDBehavior.IMPORT_UUID_CREATE_NEW);
            xmlStream.close();
            session.save();
            System.out.println("import done");

            dump(root);
        } finally {
            session.logout();
        }
    }

    /** Recursively outputs the contents of the given node. */
    private static void dump(Node node) throws RepositoryException {
// First output the node path
        System.out.println(node.getPath());
// Skip the virtual (and large!) jcr:system subtree
        if (node.getName().equals("jcr:system")) {
            return;
        }

// Then output the properties
        PropertyIterator properties = node.getProperties();
        while (properties.hasNext()) {
            Property property = properties.nextProperty();
            if (property.getDefinition().isMultiple()) {
// A multi-valued property, print all values
                Value[] values = property.getValues();
                for (int i = 0; i < values.length; i++) {
                    System.out.println(
                            property.getPath() + " = " + values[i].getString());
                }
            } else {
// A single-valued property
                System.out.println(
                        property.getPath() + " = " + property.getString());
            }
        }

// Finally output all the child nodes recursively
        NodeIterator nodes = node.getNodes();
        while (nodes.hasNext()) {
            dump(nodes.nextNode());
        }
    }
}
